define([
	'jquery',
	'underscore',
	'backbone',
	'text!templates/FolderView.html',
	'models/FolderModel',
	'views/FolderView'
], function( $, _, Backbone, FolderViewTemplate, FolderModel ) {

	var FolderView = Backbone.View.extend({

		defaults : {
			name	: 'folder',
			cover	: 'cover'
		},

		tagName:  'div',

		template: _.template( FolderViewTemplate ),

		events: {
			'mousedown'	: 'onMouseDown',
			'click'		: 'onClick'
		},

		initialize: function() {
			this.model.attributes.id	= (!!this.model.attributes.id) ? this.model.attributes.id : 0;
			this.model.attributes.name	= (!!this.model.attributes.name) ? this.model.attributes.name : this.defaults.name;
			this.model.attributes.cover	= (!!this.model.attributes.cover) ? this.model.attributes.cover : this.defaults.cover;

			this.clickDelay = 200;

			this.getHtml();
		},

		initializeDrag: function(){
			this.$el.draggable();
		},

		initializeCover: function(){
			this.$el.find(".folder").css("background-image" , "url('assets/images/"+this.model.attributes.cover+"')");
		},

		getHtml: function() {
			this.$el.html( this.template( this.model.attributes ) );
		},

		render: function($container) {
			this.initializeDrag();
			this.initializeCover();
			$container.append( this.$el );
		},

		onMouseDown: function(){
			this.lastClick = event.timeStamp;
			event.preventDefault();

			eventHandler.trigger('HomeView:sortFolders', this.model.cid);
		},

		onClick: function(event) {
			var folderElement = this.$el.children(":first");
			this.now = event.timeStamp;
			this.diffClick = this.now - this.lastClick;
			event.preventDefault();

			//TODO: change the background image

			if(this.diffClick < this.clickDelay) {
				if(folderElement.attr('class') == 'folder_open') {
					folderElement.attr('class', 'folder');
				} else {
					folderElement.attr('class', 'folder_open');
				}
			}
		}
	});

	return FolderView;
});
